# API Events

## ledger

This event is emitted whenever a new ledger version is validated on the connected server.

### Return Value

<%- renderSchema('output/ledger-event.json') %>

### Example

```javascript
api.on('ledger', ledger => {
  console.log(JSON.stringify(ledger, null, 2));
});
```

<%- renderFixture('responses/ledger-event.json') %>

## error

This event is emitted when there is an error on the connection to the server that cannot be associated to a specific request.

### Return Value

The first parameter is a string indicating the error type:
* `badMessage` - rippled returned a malformed message
* `websocket` - the websocket library emitted an error
* one of the error codes found in the [rippled Universal Errors](https://ripple.com/build/rippled-apis/#universal-errors).

The second parameter is a message explaining the error.

The third parameter is:
* the message that caused the error for `badMessage`
* the error object emitted for `websocket`
* the parsed response for rippled errors

### Example

```javascript
api.on('error', (errorCode, errorMessage, data) => {
  console.log(errorCode + ': ' + errorMessage);
});
```

```
tooBusy: The server is too busy to help you now.
```

## connected

This event is emitted after connection successfully opened.

### Example

```javascript
api.on('connected', () => {
  console.log('Connection is open now.');
});
```

## disconnected

This event is emitted when connection is closed.

### Return Value

The only parameter is a number containing the [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) send by the server.

### Example

```javascript
api.on('disconnected', (code) => {
  if (code !== 1000) {
    console.log('Connection is closed due to error.');
  } else {
    console.log('Connection is closed normally.');
  }
});
```
